import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

class VideoFullScreenPage extends StatefulWidget {
  @override
  _VideoFullScreenPageState createState() => _VideoFullScreenPageState();
}

class _VideoFullScreenPageState extends State<VideoFullScreenPage> {
  // 上个页面通过路由传过来的参数
  Map _map = {};
  late VideoPlayerController _controller;
  // 是否展示底部进度条
  bool _showProgressBar = false;
  // 当前播放
  int _position = 0;
  // 视频总长度
  int _duration = 0;

  @override
  void initState() {
    // //设置屏幕水平方向的方法
    // SystemChrome.setPreferredOrientations(
    //     [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    _map = Get.arguments;
    super.initState();
    _controller = VideoPlayerController.networkUrl(Uri.parse(_map['movieUrl']))
      ..initialize().then((value) {
        setState(() {
          _controller.play();
        });
      });
    _controller.addListener(() {
      setState(() {
        _position = _controller.value.position.inSeconds;
        _duration = _controller.value.duration.inSeconds;
      });
    });
  }

  // 时间换算方法
  String _timeConversion(int time) {
    int t1 = time ~/ 60; //分钟
    int t2 = time % 60; //秒
    return (t1 < 10 ? ('0' + t1.toString()) : t1.toString()) +
        ':' +
        (t2 < 10 ? ('0' + t2.toString()) : t2.toString());
  }

  @override
  void deactivate() {
    super.deactivate();
    // 页面退出时，切换为竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
  }

  @override
  void dispose() {
    _controller.dispose();
    // 页面退出时，切换为竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// 判断是否为横屏
    bool _isVerticalScreen =
        MediaQuery.of(context).orientation == Orientation.portrait;
    List<Widget> list = [];

    list.add(
      GestureDetector(
        // behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            _showProgressBar = !_showProgressBar;
          });
        },
        child: Container(
          color: Colors.black,
          child: Center(
            child: _controller.value.isInitialized
                ? AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: VideoPlayer(_controller),
                  )
                : CircularProgressIndicator(
                    strokeWidth: 4.0.w,
                    backgroundColor: Colors.white,
                    valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
                  ),
          ),
        ),
      ),
    );

    if (_controller.value.isInitialized) {
      list.add(AnimatedOpacity(
        opacity: _showProgressBar ? 1 : 0,
        duration: Duration(milliseconds: 300),
        child: GestureDetector(
          onTap: () {
            if (_showProgressBar) {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
              _showProgressBar = !_controller.value.isPlaying;
            }
          },
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
            size: 100,
            color: Colors.white,
          ),
        ),
      ));
      list.add(
        Positioned(
            bottom: 20.h,
            width: MediaQuery.of(context).size.width,
            child: AnimatedOpacity(
              //渐隐渐显动画效果
              opacity: _showProgressBar ? 1 : 0,
              duration: Duration(milliseconds: 300),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 5.w),
                    child: GestureDetector(
                      onTap: () {
                        if (_showProgressBar) {
                          _controller.value.isPlaying
                              ? _controller.pause()
                              : _controller.play();

                          _showProgressBar = !_controller.value.isPlaying;
                        }
                      },
                      child: Icon(
                        _controller.value.isPlaying
                            ? Icons.pause
                            : Icons.play_arrow,
                        size: _isVerticalScreen ? 30.sp : 60.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 5.w),
                    child: Text(
                      _timeConversion(_position),
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: _isVerticalScreen ? 10.sp : 20.sp),
                    ),
                  ),
                  Expanded(
                      child: Slider(
                          max: double.parse(_duration.toString()),
                          min: 0,
                          activeColor: Colors.blue,
                          inactiveColor: Colors.yellow,
                          onChanged: (double v) {
                            if (_showProgressBar) {
                              setState(() {
                                _position = int.parse(v.toStringAsFixed(0));
                                _controller
                                    .seekTo(Duration(seconds: _position));
                              });
                            }
                          },
                          value: double.parse(_position.toString()),
                          onChangeStart: (double startValue) {
                            print('Started change at $startValue');
                          },
                          onChangeEnd: (double newValue) {
                            print('Ended change on $newValue');
                          },
                          semanticFormatterCallback: (double newValue) {
                            return '${newValue.round()} dollars';
                          })),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 5.w),
                    child: Text(
                      _timeConversion(_duration),
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: _isVerticalScreen ? 10.sp : 20.sp),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (_showProgressBar) {
                        if (_isVerticalScreen) {
                          // 设置横屏
                          SystemChrome.setPreferredOrientations([
                            DeviceOrientation.landscapeLeft,
                            DeviceOrientation.landscapeRight
                          ]);
                        } else {
                          //设置竖屏
                          SystemChrome.setPreferredOrientations([
                            DeviceOrientation.portraitUp,
                          ]);
                        }
                      }

                      _controller.pause();
                      _showProgressBar = true;
                      setState(() {});
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.w),
                      child: Container(
                        child: Icon(
                          _isVerticalScreen
                              ? Icons.unfold_more
                              : Icons.unfold_less,
                          size: _isVerticalScreen ? 30.sp : 60.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )),
      );

      list.add(
        Positioned(
            top: 20.h,
            width: MediaQuery.of(context).size.width,
            // height: 40.h,
            child: AnimatedOpacity(
              //渐隐渐显动画效果
              opacity: _showProgressBar ? 1 : 0,
              duration: Duration(milliseconds: 300),
              child: GestureDetector(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          // true为横屏
                          if (_showProgressBar) {
                            if (_isVerticalScreen) {
                              Navigator.pop(context);
                            } else {
                              //设置竖屏
                              SystemChrome.setPreferredOrientations([
                                DeviceOrientation.portraitUp,
                              ]);
                            }
                          }
                        },
                        child: Icon(
                          Icons.chevron_left,
                          color: Colors.white,
                          size: _isVerticalScreen ? 30.r : 60.r,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          SmartDialog.compatible.show(
                            alignmentTemp: Alignment.bottomCenter,
                            maskColorTemp: Colors.transparent,
                            widget: Container(
                              height: 150,
                              width: double.infinity,
                              color: Colors.white,
                              alignment: Alignment.center,
                              child: ElevatedButton(
                                child: Text('add'),
                                onPressed: () => print('hello'),
                              ),
                            ),
                          );
                        },
                        child: Icon(
                          Icons.more_vert,
                          color: Colors.white,
                          size: _isVerticalScreen ? 30.r : 60.r,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
      );
    }

    return SafeArea(
      child: Scaffold(
        body: Stack(
          alignment: Alignment.center,
          children: list,
        ),
      ),
    );
  }
}
